package cn.tedu.straw.search.service.impl;

import cn.tedu.straw.search.mapper.QuestionMapper;
import cn.tedu.straw.search.repository.QuestionRepository;
import cn.tedu.straw.search.service.IQuestionService;
import cn.tedu.straw.search.vo.QuestionSearchVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class QuestionServiceImpl implements IQuestionService {
    @Autowired
    QuestionMapper questionMapper;
    @Value("${project.question.query-from-database.page-size}")
    Integer queryPageSize;
    @Autowired
    QuestionRepository questionRepository;
    @Value("${project.question.query-from-es.page-size}")
    Integer searchPageSize;

    @Override
    public PageInfo<QuestionSearchVO> getQuestionsFromDatabase(Integer pageNum) {
        if(pageNum<0||pageNum==null){
            pageNum=1;
        }
        PageHelper.startPage(pageNum,queryPageSize);
        List<QuestionSearchVO> questions=questionMapper.findQuestions();
        return new PageInfo<>(questions);
    }

    @Override
    public Page<QuestionSearchVO> search(String keyword, Integer pageNum) {
        // 确保页码值基本有效
        if (pageNum == null || pageNum < 1) {
            pageNum = 1;
        }
        // 在Spring Data处理分页时，使用0表示第1页，使用1表示第2页，以此类推
        pageNum--;
        // 准备分页参数
        Pageable pageable = PageRequest.of(pageNum, searchPageSize);
        // 执行搜索，并返回结果
        return questionRepository.queryByTitleMatchesOrContentMatches(keyword,
                keyword, pageable);
    }
}
